//
//  Dispatcher.m
//  Sensornet
//
//  Created by Chris Karr on 9/22/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "Dispatcher.h"

#define ENABLED @"Enabled"
#define VISIBLE @"Visible"
#define NAME @"Name"
#define VALUE @"Value"
#define HOSTNAME @"Hostname"
#define PORT @"Port"
#define KEY @"Key"

@implementation Dispatcher

@synthesize lastUpdate;

- (NSString *) machineName
{
	CFStringRef nameRef;
	NSString * computerName;
	nameRef = CSCopyMachineName ();
	computerName = [NSString stringWithString:(NSString *) nameRef];
	CFRelease (nameRef);
	
	return computerName;
}

- (void) awakeFromNib
{
	self.lastUpdate = [NSDate distantPast];
	
	[[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(update:) userInfo:nil repeats:YES] retain];
}

- (void) update:(NSTimer *) theTimer
{
	if ([self.lastUpdate timeIntervalSinceNow] > -10)
		return;
	
	self.lastUpdate = [NSDate date];
	
	for (NSMutableDictionary * sensor in [sensors arrangedObjects])
	{
		if ([[sensor valueForKey:ENABLED] boolValue])
		{
			for (NSMutableDictionary * host in [hosts arrangedObjects])
			{
				if ([[host valueForKey:ENABLED] boolValue] && [[host valueForKey:VISIBLE] boolValue])
				{
					NSString * sensorName = [NSString stringWithFormat:@"%@: %@", [self machineName], [sensor valueForKey:NAME], nil];
					
					NSString * urlString = [NSString stringWithFormat:@"http://%@:%d/update?name=%@&value=%@&duration=20&key=%@",
											[host valueForKey:HOSTNAME], [[host valueForKey:PORT] integerValue], 
											CFURLCreateStringByAddingPercentEscapes (kCFAllocatorDefault, (CFStringRef) sensorName, NULL, NULL, kCFStringEncodingUTF8),
											CFURLCreateStringByAddingPercentEscapes (kCFAllocatorDefault, (CFStringRef) [sensor valueForKey:VALUE], NULL, NULL, kCFStringEncodingUTF8),
											CFURLCreateStringByAddingPercentEscapes (kCFAllocatorDefault, (CFStringRef) [host valueForKey:KEY], NULL, NULL, kCFStringEncodingUTF8),
											nil];
					
					NSTask * task = [[NSTask alloc] init];
					[task setLaunchPath:@"/usr/bin/curl"];
					[task setArguments:[NSArray arrayWithObject:urlString]];
					[task setStandardOutput:[NSFileHandle fileHandleWithNullDevice]];
					[task setStandardError:[NSFileHandle fileHandleWithNullDevice]];
					
					[task launch];
					[task waitUntilExit];
					
					[task release];
				}
			}
		}
	}
}
@end
